local changying = fk.CreateSkill({
  name = "hanqing__changying",
})

Fk:loadTranslationTable{
  ["hanqing__changying"] = "长营",
  [":hanqing__changying"] = "当你使用的牌被抵消后，你可以弃置一名角色的一张牌，然后本回合结束时，因此被弃置牌的角色"..
  "可以依次使用本回合被弃置的牌，或进入<a href='hanqing__alliance_href'>连横</a>状态；若为你，你变更势力。",

  ["#hanqing__changying-choose"] = "长营：你可以弃置一名角色一张牌 ",
  ["hanqing__changying_use"] = "使用本回合被弃置的牌",
  ["hanqing__changying_horizontal"] = "进入连横状态",
  ["#hanqing__changying-use"] = "长营：你可以使用本回合被弃置的牌",
  ["#hanqing__changying-choice"] = "长营：请变更势力",
}

local U = require "packages/hanqing/util"

changying:addEffect(fk.CardEffectCancelledOut, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(changying.name) and
      table.find(player.room.alive_players, function (p)
        return not p:isNude()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p)
      return not p:isNude()
    end)
    if table.contains(targets, player) and
      not table.find(player:getCardIds("he"), function (id)
        return not player:prohibitDiscard(id)
      end) then
      table.removeOne(targets, player)
    end
    if #targets == 0 then
      room:askToCards(player, {
        min_num = 1,
        max_num = 1,
        include_equip = false,
        skill_name = changying.name,
        pattern = "false",
        prompt = "#hanqing__changying-choose",
        cancelable = true,
      })
    else
      local to = room:askToChoosePlayers(player, {
        min_num = 1,
        max_num = 1,
        targets = targets,
        skill_name = changying.name,
        prompt = "#hanqing__changying-choose",
        cancelable = true,
      })
      if #to > 0 then
        event:setCostData(self, {tos = to})
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    room:addTableMarkIfNeed(player, "hanqing__changying-turn", to.id)
    if to == player then
      room:askToDiscard(player, {
        min_num = 1,
        max_num = 1,
        include_equip = true,
        skill_name = changying.name,
        cancelable = false,
      })
    else
      local id = room:askToChooseCard(player, {
        target = to,
        flag = "he",
        skill_name = changying.name,
      })
      room:throwCard(id, changying.name, to, player)
    end
  end,
})

changying:addEffect(fk.TurnEnd, {
  anim_type = "control",
  is_delay_effect = true,
  can_trigger = function (self, event, target, player, data)
    return player:getMark("hanqing__changying-turn") ~= 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getAlivePlayers(), function (p)
      return table.contains(player:getTableMark("hanqing__changying-turn"), p.id)
    end)
    if #targets == 0 then return end
    for _, p in ipairs(targets) do
      local all_cards = {}
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              if table.contains(player.room.discard_pile, info.cardId) then
                table.insertIfNeed(all_cards, info.cardId)
              end
            end
          end
        end
      end, Player.HistoryTurn)
      local choices = {}
      if table.find(all_cards, function (id)
        return p:canUse(Fk:getCardById(id), { bypass_times = true })
      end) then
        table.insert(choices, "hanqing__changying_use")
      end
      if U.getAlliance(p) ~= "horizontal" then
        table.insert(choices, "hanqing__changying_horizontal")
      end
      if #choices > 0 then
        local choice = room:askToChoice(p, {
          choices = choices,
          skill_name = changying.name,
        })
        if choice == "hanqing__changying_use" then
          local cards = table.simpleClone(all_cards)
          while not p.dead do
            cards = table.filter(cards, function(id)
              return table.contains(room.discard_pile, id)
            end)
            if #cards == 0 then break end
            local use = room:askToUseRealCard(p, {
              pattern = cards,
              skill_name = changying.name,
              prompt = "#hanqing__changying-use",
              extra_data = {
                bypass_times = true,
                extraUse = true,
                expand_pile = cards,
              },
              skip = true,
              cancelable = #all_cards > #cards,
            })
            if use then
              table.removeOne(cards, use.card:getEffectiveId())
              room:useCard(use)
            else
              break
            end
          end
        else
          U.setAlliance(p, "horizontal")
        end
      end
      if p == player and not player.dead then
        local kingdoms = Fk:getKingdomMap("god")
        table.removeOne(kingdoms, player.kingdom)
        if #kingdoms > 0 then
          local choice = room:askToChoice(player, {
            choices = choices,
            skill_name = changying.name,
            prompt = "#hanqing__changying-choice",
          })
          room:changeKingdom(player, choice, true)
        end
      end
    end
  end,
})

return changying
